package org.tp8.sampleapp.loader.jobs.teacher;

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tp8.sampleapp.loader.exc.SampleLoaderException;
import org.tp8.sampleapp.loader.jobs.teacher.model.TeacherCase;
import org.tp8.sampleapp.loader.jobs.teacher.service.intf.TeacherInputService;
import org.tp8.sampleapp.loader.util.LoaderConstants;
import org.tp8.sampleapp.loader.util.SampleLoaderLogger;

/**
 * The Class FetchNextCaseTasklet. It initialize a logic to check which cases to
 * process and during the Tasklet execution it map the thread with the current
 * case
 * 
 */
@Component("taFetchNextCaseTasklet")
public class TAFetchNextCaseTasklet extends AbstractTeacherTasklet {

	/** The log. */
	private SampleLoaderLogger log = new SampleLoaderLogger(
			TAFetchNextCaseTasklet.class);

	@Autowired
	private TeacherInputService teacherInputService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tp8.sampleapp.loader.jobs.AbstractTasklet#executeTasklet(org.
	 * springframework.batch.core.StepContribution,
	 * org.springframework.batch.core.scope.context.ChunkContext)
	 */
	public RepeatStatus executeTasklet(StepContribution contribution,
			ChunkContext chunkContext) throws Exception {
		log.debug("entering");

		TeacherCase currentCase = fetchNext();

		if (currentCase == null) {
			ExitStatus finishedAll = new ExitStatus(
					LoaderConstants.FINISHED_ALL);
			contribution.setExitStatus(finishedAll);
		} else {
			setCurrentCase(currentCase);
		}

		log.debug("Loaded case: " + currentCase);

		return RepeatStatus.FINISHED;
	}

	/**
	 * Fetch next migration case.
	 * 
	 * @return the content migration case
	 * @throws SampleLoaderException
	 */
	private TeacherCase fetchNext() throws SampleLoaderException {
		Long caseId = teacherInputService.fetchNextCaseID();

		// If no case id remains, exit
		if (caseId == null) {
			return null;
		}

		// TODO: Fetch case
		TeacherCase result = teacherInputService.loadTeacher(caseId);

		return result;
	}

}
